﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Text.RegularExpressions;

namespace UpdateSetupVersion
{
    class Program
    {
        static void Main(string[] args) {
            //Take one command-line arguments
            if(args.Length != 1) {
                Console.WriteLine("usage: UpdateSetupVersion.exe <setup.vdproj>");
                Environment.Exit(1);
            }

            //Read the project file
            string configFilePath = args[0];
            string config = File.ReadAllText(configFilePath);
            
            //Don't bother with a backup

            //Find product version
            Regex re = new Regex(@"(""ProductVersion"" = ""8:)(\d+(\.\d+)*)""");
            Match pvMatch = re.Match(config);
            if(!(pvMatch.Success)){
                Console.WriteLine("Could not find ProductVersion");
                Environment.Exit(1);
            }

            string currentVersion = pvMatch.Groups[2].Value;
            Version cv = Version.Parse(currentVersion);
            //Increment the version
            Version newVersion  = new Version(cv.Major, cv.Minor, cv.Build + 1);
            Console.WriteLine("New Setup Version: {0}", newVersion);

            config = re.Replace(config, string.Format("${{1}}{0}\"", newVersion));


            //Find the ProductCode
            re = new Regex(@"(""ProductCode"" = ""8:)(\{.+\})""");
            pvMatch = re.Match(config);
            if(!(pvMatch.Success)) {
                Console.WriteLine("Could not find ProductCode");
                Environment.Exit(1);
            }
            Guid newProductCode = Guid.NewGuid();
            config = re.Replace(config, string.Format("{0}{{{1}}}\"", "${1}", newProductCode.ToString().ToUpper()));
            Console.WriteLine("New Product Code: {0}", newProductCode);

            //Find the PackageCode
            re = new Regex(@"(""PackageCode"" = ""8:)(\{.+\})""");
            pvMatch = re.Match(config);
            if(!(pvMatch.Success)) {
                Console.WriteLine("Could not find PackageCode");
                Environment.Exit(1);
            }
            Guid newPacakgeCode = Guid.NewGuid();
            config = re.Replace(config, string.Format("{0}{{{1}}}\"", "${1}", newPacakgeCode.ToString().ToUpper()));
            Console.WriteLine("New Package Code: {0}", newPacakgeCode);

            File.WriteAllText(configFilePath, config);

            //Console.ReadLine();

        }
    }
}
